﻿using System;
using System.Text;
using System.Net;
using System.IO;


namespace Wusong.Gold.DataService
{
    public interface IWriterBase
    {

        void Write(GoldMsg value);
    }

    public class PlainTextWriter : IWriterBase, IDisposable
    {
        private string _filePath;
        private FileStream stream;
        private StreamWriter sw;

        private object synObj = new object();


        public PlainTextWriter(string filePath)
        {
            _filePath = filePath;
            if (string.IsNullOrEmpty(_filePath))
            {
                _filePath = @"f:\onlineprice.text";
            }

            try
            {
                stream = new FileStream(_filePath, FileMode.OpenOrCreate);
                sw = new StreamWriter(stream, Encoding.Default);
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public void Write(GoldMsg value)
        {
            try
            {
                lock (synObj)
                {
                    sw.Write(value.FormatString);
                    sw.Flush();
                }
            }
            catch (IOException ioEx)
            {
                Console.WriteLine(ioEx.Message);
                Console.ReadKey();
                sw.Close();
                stream.Close();
                sw.Dispose();
                stream.Dispose();
            }
        }

        public void Dispose()
        {
            if (sw != null)
                sw.Dispose();

            if (stream != null)
                stream.Dispose();
        }

    }

}
